using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using cframework_xlua;
using System.ComponentModel;
using Newtonsoft.Json;
using static UnityEngine.EventSystems.EventTrigger;
using System.Reflection;


namespace cframework_xlua
{
    [CreateAssetMenu(menuName = "cframework_xlua/BuildPlayerSetting_Android")]
    public class BuildPlayerSetting_Android : BuildPlayerSetting
    {
        public bool useCustomKeystore = true;
        public TextAsset keystoreFile;
        public string keystorePassword;
        public string keyaliasName;
        public string keyaliasPassword;

        public void SetAndroidSdkConfig(string androidSdkPath, string androidNdkPath, string javaHome)
        {
            EditorPrefs.SetString("AndroidSdkRoot", androidSdkPath);
            EditorPrefs.SetString("AndroidNdkRootR21D", androidNdkPath);
            EditorPrefs.SetString("JdkPath", javaHome);

            EditorPrefs.SetInt("JdkUseEmbedded", string.IsNullOrEmpty(javaHome) ? 1 : 0);
            EditorPrefs.SetInt("NdkUseEmbedded", string.IsNullOrEmpty(androidNdkPath) ? 1 : 0);
            EditorPrefs.SetInt("SdkUseEmbedded", string.IsNullOrEmpty(androidSdkPath) ? 1 : 0);
        }


        public override bool SetPlatformConfig()
        {
            string gradlePath = deviceToolPaths.GetToolPath("GRADLE_PATH");
            EditorUserBuildSettings.exportAsGoogleAndroidProject = !string.IsNullOrEmpty(gradlePath);

            string java_home = deviceToolPaths.GetToolPath("JAVA_HOME");
            string android_sdk_home = deviceToolPaths.GetToolPath("ANDROID_SDK_HOME");
            string android_ndk_home = deviceToolPaths.GetToolPath("ANDROID_NDK_HOME");

            var androidKeyStoreUtil = this;

            SetAndroidSdkConfig(android_sdk_home, android_ndk_home, java_home);
            if (androidKeyStoreUtil != null)
            {
                bool SetKeyStore = true;
                if (androidKeyStoreUtil.useCustomKeystore)
                {
                    if (androidKeyStoreUtil.keystoreFile == null)
                    {
                        EditorUtility.DisplayDialog("error", "android key store path is empty", "ok");
                        return false;
                    }
                    else
                    {
                        if (!System.IO.File.Exists(androidKeyStoreUtil.keyStoreFullPath))
                        {
                            //if (EditorUtility.DisplayDialog("warning", "android key store path not found", "create", "dont use CustomKeyStore"))
                            //{
                            //    var jdkPath = EditorPrefs.GetString("JdkPath");
                            //    if (!androidKeyStoreUtil.CreateKeyStoreFile(jdkPath))
                            //    {
                            //        EditorUtility.DisplayDialog("error", "create android key store file failed", "ok");
                            //        return false;
                            //    }
                            //}
                            //else
                            {
                                SetKeyStore = false;
                            }
                        }
                    }
                }

                androidKeyStoreUtil.SetKeyStore(SetKeyStore);
            }

            return true;
        }


        public void SetKeyStore(bool enable)
        {
            if (!useCustomKeystore || keystoreFile == null || !enable)
            {
                UnityEditor.PlayerSettings.Android.useCustomKeystore = false;
            }
            else
            {
                UnityEditor.PlayerSettings.Android.useCustomKeystore = true;
                UnityEditor.PlayerSettings.Android.keystoreName = keyStoreFullPath;
                UnityEditor.PlayerSettings.Android.keystorePass = keystorePassword;
                UnityEditor.PlayerSettings.Android.keyaliasName = keyaliasName;
                UnityEditor.PlayerSettings.Android.keyaliasPass = keyaliasPassword;
            }
        }

        public string keyStoreFullPath
        {
            get
            {
                return AssetDatabase.GetAssetPath(keystoreFile);
            }
        }

        [ContextMenu("CreateAndroidKeyStoreFile")]
        public void CreateAndroidKeyStoreFile()
        {
            var jdkPath = EditorPrefs.GetString("JdkPath");
            if (!CreateKeyStoreFile(jdkPath))
            {
                EditorUtility.DisplayDialog("error", "create android key store file failed", "ok");
            }
        }

        public bool CreateKeyStoreFile(string java_home)
        {
            if(this.keystoreFile != null)
            {
                return false;
            }

            var assetPath = AssetDatabase.GetAssetPath(this);

            string ext = System.IO.Path.GetExtension(assetPath);
            string keystoreFilePath = assetPath = assetPath.Remove(assetPath.Length - ext.Length) + ".keystore.bytes";

            if(System.IO.File.Exists(keystoreFilePath))
            {
                return false;
            }


            if (string.IsNullOrEmpty(keystorePassword)) keystorePassword = CommonUtil.GetTimeStamp().ToString();
            if (string.IsNullOrEmpty(keyaliasName)) keyaliasName = CommonUtil.GetTimeStamp().ToString();
            if (string.IsNullOrEmpty(keyaliasPassword)) keyaliasPassword = CommonUtil.GetTimeStamp().ToString();

            var keytoolPath = this.deviceToolPaths.GetCmdToolPath("keytool");
            if(string.IsNullOrEmpty(keytoolPath))
            {
                keytoolPath = $"{java_home}/bin/keytool";
            }

            if(!System.IO.File.Exists(keytoolPath))
            {
                return false;
            }

            var ret = CommandLineTool.RunCommand2(keytoolPath, $"-genkey -validity 2000 -keyalg RSA -dname \"CN = Test, OU = Test, O = Test, L = Test, S = Test, C = Test\" -keystore {keystoreFilePath} -storepass {keystorePassword} -alias {keyaliasName} -keypass {keyaliasPassword}", System.IO.Path.GetDirectoryName(Application.dataPath));

            if (ret.ExitCode != 0)
            {
                Debug.LogError("output: " + ret.StdOut);
                Debug.LogError("error: " + ret.StdErr);
                return false;
            }

            AssetDatabase.Refresh();

            keystoreFile = AssetDatabase.LoadAssetAtPath<TextAsset>(keystoreFilePath);

            return true;
        }
    }
}